<?php

declare(strict_types=1);

namespace App\Common\Service\Affiliate;

use App\Setting\Service\SettingConfigService;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Hyperf\Codec\Packer\JsonPacker;
use Hyperf\Contract\PackerInterface;
use Hyperf\Coroutine\Coroutine;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Guzzle\CoroutineHandler;
use function Hyperf\Collection\collect;

abstract class AbstractAffiliateService
{
    #[Inject]
    protected SettingConfigService $configService;

    protected Client $client;

    protected PackerInterface $packer;

    protected string $errMsg = '';

    public function __construct(PackerInterface $packer = null)
    {
        $handler = null;
        if (Coroutine::inCoroutine()) {
            $handler = new CoroutineHandler();
        }

        $this->client = new Client([
            'timeout' => 3,
            'handler' => $handler,
        ]);
        $this->packer = $packer ?? new JsonPacker();
    }

    abstract public function getAuthUrl(array $params): string;

    abstract public function getAppKeyName(): string;

    abstract public function getAppSecretName(): string;

    public function getAppKeyAndSecret(): array
    {
        $config = $this->configService->getConfigByGroupKey('affiliate_oauth_config');
        $config = collect($config)->pluck('value', 'key')->toArray();
        return [
            'appKey' => $config[$this->getAppKeyName()] ?? '',
            'appSecret' => $config[$this->getAppSecretName()] ?? ''
        ];
    }

    public function getDomain()
    {
        if (\Hyperf\Support\env('IS_LOCAL')) {
            return 'http://www.myxcxdz.com';
        }
        return $this->configService->getConfigByKey('ch_api_url')['value'];
    }


    protected function get(string $uri, array $data = [])
    {
        try {
            $response = $this->client->get($uri, [
                    'query' => $data,
                    'timeout' => 3
                ]
            );

            $data = $this->packer->unpack((string) $response->getBody());
            return $data;
        } catch (GuzzleException $e) {
            $this->errMsg = $e->getMessage();
            return false;
        }
    }

    protected function post(string $uri, array $data = [])
    {
        try {
            $response = $this->client->post($uri, [
                    'json' => $data,
                    'timeout' => 3
                ]
            );

            $data = $this->packer->unpack((string) $response->getBody());
            return $data;
        } catch (GuzzleException $e) {
            $this->errMsg = $e->getMessage();
            return false;
        }
    }
}